#pragma once


//只负载代码的编译

#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include "../comm/util.hpp"
#include "../comm/log.hpp"

namespace ns_compiler
{
    using namespace ns_util;
    using namespace ns_log;
    class Compiler
    {
    public:
        //返回值 : 成功(true) ,失败(false)
        //传入参数 : 文件名
        static bool compile(const std::string& file_name)
        {
            pid_t pid = fork();
            if(pid < 0)
            {
                LOG(ERROR) << "内部错误,子进程创建失败" << "\n";
                return false;
            }
            else if(pid == 0)
            {
                //child
                umask(0);
                int _stderr = open(PathUtil::CompilerError(file_name).c_str(),O_CREAT | O_WRONLY,0644);
                if(_stderr < 0)
                {
                    LOG(WARNING) << "没有成功形成stderr文件" << "\n";
                    exit(1);
                }
                dup2(_stderr,2);

                execlp("g++","g++","-o",PathUtil::Exe(file_name).c_str(),
                PathUtil::Src(file_name).c_str(),"-D","COMPILER_ONLINE","-std=c++11",nullptr);
                LOG(ERROR) << "启动编译失败,可能是参数问题" << "\n";
                exit(2);
            }
            else
            {
                waitpid(pid,nullptr,0);
                if(FileUtil::IsFileExists(PathUtil::Exe(file_name)))
                {
                    LOG(INFO) << PathUtil::Src(file_name) << " 编译成功!" << "\n";
                    return true;
                }
            }
            LOG(ERROR) << "启动编译失败,没有形成可执行程序" << "\n";
            return false;
        }
    };
}


